﻿using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GetRequestDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            // 1.创建 客户端
            RestClient client = new RestClient("http://10.5.160.125:80/");
            // 如果需要登录认证
            //client.Authenticator = new HttpBasicAuthenticator("username", "password");

            // 2.创建 GET请求
            RestRequest request = new RestRequest("carlock/frmCustomPlatformCfg", Method.GET);

            // 2.1 添加请求头
            request.AddHeader("accept", "application/json");
            request.AddHeader("Content-Type", "application/json-patch+json");

            // 2.2 添加请求正文
            request.AddJsonBody(new { Type = 1, Dev = 1, Ch = 1, Data = new { xxx = 1, yyy = 2 } });
            // 如果是字符串，也可以使用 Newtonsoft.Json 序列化成对象
            //var body = JsonConvert.DeserializeObject("{\"Type\":1,\"Dev\":1,\"Ch\":1,\"Data\":{}}");
            //request.AddJsonBody(body);

            // 2.3 添加请求参数
            request.AddParameter("Type", 1);
            request.AddParameter("Dev", 1);
            request.AddParameter("Ch", 1);
            request.AddParameter("Data", new { xxx = 1, yyy = 2 });
            // 如果是 Url 参数，也可以使用 ParameterType.UrlSegment 来标注
            // var request = new RestRequest("health/{entity}/status")
            // request.AddParameter("entity", "s2", ParameterType.UrlSegment);

            // 3.执行，得到响应对象
            var response = client.Execute<ServerResponse>(request);
            Console.WriteLine(response.Data.Result);

            return View();
        }
    }

    class ServerResponse
    {
        public int Result { get; set; }
        public object Data { get; set; }
    }
}